package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.ParseException;
import java.util.Map;

/**
 * @program: itcast_health
 * @create: 2019-10-25 16:48
 * @author: li he
 * @description:
 *
 * {
 * idCard=123456789012345,
 * sex=1,
 * name=李贺,
 * setMealId=5,
 * validateCode=1434,
 * telephone=13899998888,
 * orderDate=2019-10-27}
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("submit")
    public Result submit(@RequestBody Map<String, Object> map) {

        String validateCodeParam = String.valueOf(map.get("validateCode"));
        String telephone = String.valueOf(map.get("telephone"));
        String validateCodeRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_ORDER + telephone);

        if (!(validateCodeRedis != null && validateCodeRedis.equals(validateCodeParam))){
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
        try {
            return orderService.add(map);
        } catch (ParseException e) {
            System.out.println("e = " + e +": 日期格式转换异常 ! ! ! !");
            throw new RuntimeException(e);
        }
    }
    @RequestMapping("findById")
    public Result findById(Integer id){
        try {
            Map<String,Object> map = orderService.findById(id);
            return new Result(true,MessageConst.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConst.QUERY_ORDER_FAIL);
        }
    }
}